package org.beangle.notification.mail

import java.util.ArrayList
import java.util.Date
import java.util.List
import javax.mail.internet.InternetAddress
import org.beangle.commons.lang.Assert
import org.beangle.commons.lang.Strings
import org.beangle.notification.AbstractMessage
//remove if not needed
import scala.collection.JavaConversions._

class MailMessage extends AbstractMessage {

  var from: InternetAddress = null

  var to = new collection.mutable.ArrayBuffer[InternetAddress]

  var cc = new collection.mutable.ArrayBuffer[InternetAddress]

  var bcc = new collection.mutable.ArrayBuffer[InternetAddress]

  var sentAt: Date = _

  def getEncoding(): String = {
    Strings.substringAfter(contentType, "charset=")
  }

  def recipients(): List[String] = {
    val recipients = new ArrayList[String]()
    for (address <- to) recipients.add(address.toString)
    for (address <- cc) recipients.add(address.toString)
    for (address <- bcc) recipients.add(address.toString)
    recipients
  }

  def this(subject: String, text: String, sendTo: String) {
    this()
    to = MimeUtils.parseAddress(sendTo, getEncoding)
    this.subject = subject
    this.text = text
  }

  def this(subject: String,
    text: String,
    sendTo: String,
    sendCc: String,
    sendBcc: String) {
    this()
    to = MimeUtils.parseAddress(sendTo, getEncoding)
    cc = MimeUtils.parseAddress(sendCc, getEncoding)
    bcc = MimeUtils.parseAddress(sendBcc, getEncoding)
    this.subject = subject
    this.text = text
  }

  def from(from: String): MailMessage = {
    val froms = MimeUtils.parseAddress(from, getEncoding)
    if (froms.size > 0) this.from = froms.get(0)
    this
  }

  def addTo(sendTo: String) {
    this.to.addAll(MimeUtils.parseAddress(sendTo, getEncoding))
  }

  def addCc(sendCc: String) {
    this.cc.addAll(MimeUtils.parseAddress(sendCc, getEncoding))
  }

  def addBcc(sendBcc: String) {
    this.bcc.addAll(MimeUtils.parseAddress(sendBcc, getEncoding))
  }
}
